Imports System.Windows.Forms
Imports System.Text.RegularExpressions

Imports Extensibility
Imports EnvDTE
Imports EnvDTE80


Public Class Regexer

#Region "Private Members"

	Private mApplication As EnvDTE80.DTE2
    Private mTextSelection As EnvDTE.TextSelection
    Private mSelectedText As String

#End Region


#Region "Public Properties"

    Public Property Application() As EnvDTE80.DTE2
        Get
            Return mApplication
        End Get
        Set(ByVal value As EnvDTE80.DTE2)
            mApplication = value
        End Set
    End Property

#End Region


#Region "Private Methods"

    Private Sub InsertText()

        Me.mApplication.UndoContext.Open("Regexer Replace")

        Me.mTextSelection.Delete()

        Me.mTextSelection.Insert(Me.ReplaceText, 1)

        Me.mApplication.UndoContext.Close()

    End Sub

    Private Function ReplaceText() As String

		Try

			Me.StatusLabel.Text = ""

			Return Regex.Replace(Me.mSelectedText, Me.FindTextBox.Text, Me.ReplaceTextBox.Text, RegexOptions.Multiline Or RegexOptions.IgnorePatternWhitespace)

		Catch ex As Exception

			Me.StatusLabel.Text = "Regular expression syntax is invalid."

		End Try

        Return Me.mSelectedText

    End Function

    Private Function GetSelectedText() As String

		Me.mTextSelection = DirectCast(Me.mApplication.ActiveDocument.Selection, EnvDTE.TextSelection)

		If Me.mTextSelection.Text.Length = 0 Then
			Me.mTextSelection.SelectAll()
		End If

		Return Me.mTextSelection.Text

    End Function

#End Region


#Region "Event Handlers"

    Private Sub Patterns_Validated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindTextBox.Validated, ReplaceTextBox.Validated

        DirectCast(sender, TextBox).ForeColor = Drawing.Color.Green

        Me.PreviewTextBox.Text = Me.ReplaceText

    End Sub

    Private Sub Regexer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Me.mSelectedText = Me.GetSelectedText()

        Me.PreviewTextBox.Text = Me.ReplaceText()

    End Sub

    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Replace_Button.Click

        Me.InsertText()

        Me.DialogResult = System.Windows.Forms.DialogResult.OK

        Me.Close()

    End Sub

    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click

		Me.DialogResult = System.Windows.Forms.DialogResult.Cancel

		Me.Close()

	End Sub

#End Region

End Class
